﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using Portal.Environment;
using Portal.Language;
using Portal.Interface;

namespace Portal.CMS
{
    public class UpdateAttachmentsNews : WebPart
    {
        public override string WebPartId
        {
            get
            {
                return "UpdateAttachmentsNews";
            }
        }

        public override string Title
        {
            get
            {
                return ResourceBLL.GetText(WebPartId, "Title", "Cập nhật danh sách tài liệu đính kèm tin");
            }
        }

        public override string Description
        {
            get
            {
                return ResourceBLL.GetText(WebPartId, "Description", "");
            }
        }


        public override void LoadSubControls(System.Web.UI.WebControls.PlaceHolder pl, System.Web.UI.Page Page, LoadParamCls LoadParamCls)
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(UpdateAttachmentsNews));
            string NewsId = (string)System.Web.HttpContext.Current.Request["NewsId"];
            NewsCls NewsCls = new NewsBLL().CreateModel(Environment.Environments.ActiveLanguage, NewsId);

            string RetHtml =
                Environments.GetFormDialog(
                    WebPartUtilities.AttachJavascript("Portal.CMS", "News.js") +
                    "<div class=cssHeading>" + NewsCls.Subject + "</div>\r\n" +
                    "<div id=\"divNewsRelations\">" + GetNewsAttachmentsForm(NewsCls.belongSite, NewsCls) + "</div><div id=divAlreadyNewsRelation>" + GetAlreadyAttachmentsNews(NewsId) + "</div>", Title);
            pl.Controls.Add(new System.Web.UI.LiteralControl(RetHtml));
        }


        [AjaxPro.AjaxMethod]
        public string GetAlreadyAttachmentsNews(string NewsId)
        {
            DataTable dtAttachmentsNews = new NewsBLL().ReadingAttachmentsNews(NewsId);

            string RetHtml = "<div class=cssHeading>" + GetText("NewsAttachmentsListHeading", "Danh sách tài liệu đính kèm") + " (" + dtAttachmentsNews.Rows.Count.ToString("#,##0") + ")</div>";

            if (dtAttachmentsNews.Rows.Count == 0)
            {
                RetHtml += "<div class=\"cssNoDataAttachment\">" + ResourceBLL.GetText(WebPartId, "cssNoDataAttachment", "Chưa có tài liệu nào được đính kèm!") + "</div>";
            }
            else
            {
                RetHtml +=
                        //"<div><input type=\"hidden\" id=\"txtMaxRelationNews\" value=\"" + dtAttachmentsNews.Rows.Count + "\"><input type=\"button\" onclick=\"javascript:ClientSaveIndexAttachmentsNews('" + NewsId + "');\" value=\"" + GetText("saveIndexRelationNews", "Cập nhật thứ tự hiện thị") + "\"></div>\r\n" +
                        "<table class=cssNewsContent>" +
                        "  <tr>" +
                        "      <th class=cssCol1>" + ResourceBLL.GetText(WebPartId, "Index", "STT") + "</th>" +
                        "      <th class=cssCol1>" + ResourceBLL.GetText(WebPartId, "UploadFileName", "Tên file") + "</th>" +
                        "      <th class=cssCol1>" + ResourceBLL.GetText(WebPartId, "FriendlyText", "Tên hiển thị") + "</th>" +
                        "      <th class=cssCol2>" + ResourceBLL.GetText(WebPartId, "EntryDate", "Ngày tạo") + "</th>" +

                         //"     <th class=cssCol1>Thứ tự hiển thị</th>" +
                         "      <th class=cssCol3>Chức năng</th>" +
                        " </tr>";
                for (int iIndex = 0; iIndex < dtAttachmentsNews.Rows.Count; iIndex++)
                {
                    string NewsAttachsId = (string)dtAttachmentsNews.Rows[iIndex]["NewsAttachsId"];
                    string UploadFileName = "";
                    try
                    {
                        UploadFileName = (string)dtAttachmentsNews.Rows[iIndex]["UploadFileName"];
                    }
                    catch { }

                    string FriendlyTitle = "";
                    try
                    {
                        FriendlyTitle = (string)dtAttachmentsNews.Rows[iIndex]["FriendlyTitle"];
                    }
                    catch { }

                    DateTime EntryDate = (DateTime)dtAttachmentsNews.Rows[iIndex]["EntryDate"];

                    string AttachmentId = (string)dtAttachmentsNews.Rows[iIndex]["fk_AttachmentId"];

                    RetHtml +=
                           "  <tr onMouseOver=\"this.className='highlight'\" onMouseOut=\"this.className='normal'\">" +
                           "      <td valign=top>" + (iIndex + 1) + "</td>" +
                           "      <td valign=top>" + UploadFileName + "</td>" +
                           "      <td valign=top>" + FriendlyTitle + "</td>" +
                           "      <td valign=top>" + EntryDate.ToString("dd/MM/yyyy") + "</td>" +
                           //"      <td valign=top><input type=hidden id=\"txtRelationNewsId" + iIndex + "\" value=\"" + NewsAttachsId + "\"> <input class=\"cssIndexRelationNews\" id=\"txtIndex" + iIndex + "\" value=\"" + (iIndex + 1) + "\"></td>" +
                           "      <td><a href=\"javascript:ClientResetDocumentContent('" + NewsId + "','" + AttachmentId + "');\">" + ResourceBLL.GetText(WebPartId, "DeleteConten", "(Xóa)") + "</a></td>" +
                           " </tr>";
                }
                RetHtml += "</table>";
            }
            return RetHtml;
        }


        [AjaxPro.AjaxMethod]
        public string SearchRelationNews(
            string SrcNewsId,
            string belongSite,
            string Keyword,
            string fromDate,
            string toDate,
            int WorkflowStatusIndex,
            string SGroupNewsItemId,
            string Source,
            int PageIndex)
        {
            try
            {
                Environment.Environments.CheckSessionTimeOut(true);
                //if(Keyword.Trim().Length==0 && Source.Trim().Length==0)throw new Exception(ResourceBLL.GetText(WebPartId,"KeywordIsMissing","Chưa nhập từ khóa tìm kiếm..."));
                string RetHtml = "";
                Keyword = Environment.WebPartUtilities.CorrectForSearch(Keyword);
                Source = Environment.WebPartUtilities.CorrectForSearch(Source);
                fromDate = Environment.WebPartUtilities.CorrectForSearch(fromDate);
                toDate = Environment.WebPartUtilities.CorrectForSearch(toDate);

                DataTable dtNews = new NewsBLL().SearchingForRelation(SrcNewsId, belongSite, Keyword, fromDate, toDate, WorkflowStatusIndex, Source, SGroupNewsItemId);
                int ItemPerPage = 20;
                int MaxPage = dtNews.Rows.Count / ItemPerPage;
                if (dtNews.Rows.Count % ItemPerPage != 0) MaxPage++;
                int StartIndex = PageIndex * ItemPerPage;
                int EndIndex = StartIndex + ItemPerPage;
                if (EndIndex > dtNews.Rows.Count) EndIndex = dtNews.Rows.Count;
                string SelectPageText =
                   ResourceBLL.GetText(WebPartId, "PageText", "Trang") + ": <select id=divSelectSearchNewsPage>";
                for (int iIndex = 0; iIndex < MaxPage; iIndex++)
                {
                    if (PageIndex == iIndex)
                    {
                        SelectPageText += "<option selected>" + (iIndex + 1) + "</option>";
                    }
                    else
                    {
                        SelectPageText += "<option>" + (iIndex + 1) + "</option>";
                    }
                }
                SelectPageText += "</select><input type=button value=\"Go\" onclick=javascript:ClientSearchNewsRelation();>";
                if (MaxPage <= 1) SelectPageText = "";


                if (dtNews.Rows.Count == 0)
                {
                    RetHtml += "<div class=\"cssNoDataSearchNews\">" + ResourceBLL.GetText(WebPartId, "cssNoDataSearchNews", "Không có tin tức nào thỏa mãn điều kiện tìm kiếm!") + "</div>";
                }
                else
                {
                    RetHtml += SelectPageText +
                    "<table class=cssNewsContent>" +
                           "  <tr>" +
                           "      <th class=cssCol0>#</th>" +
                           "      <th class=cssCol1>" + ResourceBLL.GetText(WebPartId, "UploadFileName", "File") + "</th>" +
                           "      <th class=cssCol2></th>" +
                           " </tr>";
                    for (int iIndex = StartIndex; iIndex < EndIndex; iIndex++)
                    {
                        string DestNewsId = (string)dtNews.Rows[iIndex]["NewsId"];
                        string GroupNewsId = (string)dtNews.Rows[iIndex]["GroupNewsId"];
                        string GroupNewsItemId = (string)dtNews.Rows[iIndex]["GroupNewsItemId"];
                        string SubjectText = "";
                        try
                        {
                            SubjectText = (string)dtNews.Rows[iIndex][Environments.ActiveLanguage + "Subject"];
                        }
                        catch { }


                        RetHtml +=
                               "  <tr onMouseOver=\"this.className='highlight'\" onMouseOut=\"this.className='normal'\">" +
                               "      <td valign=top>" + (iIndex + 1) + "</td>" +
                               "      <td valign=top class=cssTdSubjectText>" + SubjectText + "</td>" +
                               "      <td valign=top nowrap><div id=\"divAddNewsRelationItem_" + DestNewsId + "\"><a href=\"javascript:ClientAddNewsRelation('" + DestNewsId + "');\">" + ResourceBLL.GetText(WebPartId, "AddNewsRelation", "Đưa vào") + "</a></div></td>" +
                               " </tr>";
                    }
                    RetHtml += "</table>";
                }
                return RetHtml;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        [AjaxPro.AjaxMethod]
        public string ServerSideGetGroupNewsItem(string belongSite, string SGroupNewsItemId)
        {
            try
            {
                Environment.Environments.CheckSessionTimeOut(true);
                string SelectGroupNewsText =
                   "<select id=drpSelectGroupNewsItem>";
                DataTable dtGroupNewsItems = new GroupNewsBLL().ReadingGroupNewsItemsForSearch(belongSite);
                for (int iIndex = 0; iIndex < dtGroupNewsItems.Rows.Count; iIndex++)
                {
                    string GroupNewsItemName = (string)dtGroupNewsItems.Rows[iIndex][Environments.ActiveLanguage + "GroupNewsItemName"];
                    string GroupNewsItemId = (string)dtGroupNewsItems.Rows[iIndex]["GroupNewsItemId"];
                    if (GroupNewsItemId.Equals(SGroupNewsItemId))
                    {
                        SelectGroupNewsText += "<option selected value=\"" + GroupNewsItemId + "\">" + GroupNewsItemName + "</option>";
                    }
                    else
                    {
                        SelectGroupNewsText += "<option  value=\"" + GroupNewsItemId + "\">" + GroupNewsItemName + "</option>";
                    }
                }
                SelectGroupNewsText += "</select>";
                if (dtGroupNewsItems.Rows.Count == 0) SelectGroupNewsText = "?";
                return SelectGroupNewsText;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        string GetNewsAttachmentsForm(string ActiveSite, NewsCls NewsCls)
        {
            string belongSite = "vie";
            string DocumentItemUrl =
                WebPartUtilities.AttachJavascript("Portal.CMS", "News.js") +
                "<a href=\"javascript:ClientUploadDocumentContent('" + belongSite + "','" + NewsCls.NewsId + "');\">" + ResourceBLL.GetText(WebPartId, "UploadDocument", "(Thêm tài liệu đính kèm)") + "</a><br>";

            return DocumentItemUrl;
        }


        [AjaxPro.AjaxMethod]
        public string ServerSideNews(
            string ActiveLanguage,
            string NewsId,
            string Subject,
            string ImageUrl,
            string ShortContent,
            string Body,
            string SearchKeyword,
            string Source,
            string sEntryDate,
            bool AttachedDoc,
            bool AttachedImage,
            bool AttachedVideo)
        {
            try
            {
                Environment.Environments.CheckSessionTimeOut(true);
                if (Subject.Trim().Length == 0) throw new Exception(ResourceBLL.GetText(WebPartId, "EnterSubject", "Nhập tiêu đề!"));
                if (ShortContent.Trim().Length == 0) throw new Exception(ResourceBLL.GetText(WebPartId, "InputShortContent", "Nhập mô tả!"));
                if (Body.Trim().Length == 0) throw new Exception(ResourceBLL.GetText(WebPartId, "InputBody", "Nhập nội dung!"));

                ShortContent = System.Web.HttpUtility.HtmlDecode(ShortContent);
                Body = System.Web.HttpUtility.HtmlDecode(Body);

                PermissionTypeCls PermissionTypeCls = Environments.FindPermissionType(
                new GroupNews().PermissionTypes, "GroupNewsItems");
                NewsCls NewsCls = new NewsBLL().CreateModel(Environments.ActiveLanguage, NewsId);
                GroupNewsItemCls GroupNewsItemCls = new GroupNewsBLL().CreateModelItem(Environments.ActiveLanguage, NewsCls.GroupNewsItemId);
                Environment.Permission.CheckPermission(
                    Environment.Environments.CurrentLoginUser.LoginName,
                    PermissionTypeCls.PermissionTypeCode,
                             "UpdateRelationNewsItem", GroupNewsItemCls.GroupNewsItemId, GroupNewsItemCls.Owner, true);

                bool CheckOk = Environment.FuncUtilities.checkVnDate(sEntryDate);
                if (CheckOk == false) throw new Exception(ResourceBLL.GetText(WebPartId, "InvalidDate", "Ngày tháng nhập sai!"));
                DateTime EntryDate = Environment.FuncUtilities.VNDateToDate(sEntryDate);

                string ShortContentForSearch = ShortContent;
                string BodyForSearch = Body;
                new NewsBLL().SaveNews(null, ActiveLanguage, GroupNewsItemCls.GroupNewsItemId, NewsId, Subject, ImageUrl, ShortContent, Body, SearchKeyword, Source, EntryDate, AttachedDoc ? 1 : 0, AttachedVideo ? 1 : 0, AttachedImage ? 1 : 0, NewsCls.EmbVideo, NewsCls.EmbAudio);
                return ResourceBLL.GetText(WebPartId, "MessageUpdateRelationNewsOk", "Sửa tin tức thành công!");
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string GetLoadDataMsg()
        {
            return ResourceBLL.GetText(WebPartId, "LoadingDataText", "Đang đọc dữ liệu...");
        }


        [AjaxPro.AjaxMethod]
        public string GetSubject(string ActiveLanguage, string NewsId)
        {
            try
            {
                NewsCls NewsCls = new NewsBLL().CreateModel(ActiveLanguage, NewsId);
                return NewsCls.Subject;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        [AjaxPro.AjaxMethod]
        public string GetShortContent(string ActiveLanguage, string NewsId)
        {
            try
            {
                NewsCls NewsCls = new NewsBLL().CreateModel(ActiveLanguage, NewsId);
                return NewsCls.ShortContent;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        [AjaxPro.AjaxMethod]
        public string GetBody(string ActiveLanguage, string NewsId)
        {
            try
            {
                NewsCls NewsCls = new NewsBLL().CreateModel(ActiveLanguage, NewsId);
                return NewsCls.Body;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string GetProcessingText()
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                string Url = Environment.Environments.GetActiveThemeUrl() + "/Global/Loading.gif";
                return "<img src=\"" + Url + "\"><a class=cssProcessing>" + ResourceBLL.GetText(WebPartId, "ProcessingText", "Đang đọc dữ liệu...") + "</a>";
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string ServerSideAddNewsRelation(string SrcNewsId, string NewsId)
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                new NewsBLL().AddNewsRelation(SrcNewsId, NewsId);
                return GetAlreadyAttachmentsNews(SrcNewsId);
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public string ServerSideRemoveNewsRelation(string NewsId, string NewsRelationId)
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                new NewsBLL().RemoveNewsRelation(NewsRelationId);
                return GetAlreadyAttachmentsNews(NewsId);// GetText("RemoveOk", "Loại bỏ tin liên quan thành công!");
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        public override bool RunStandalone
        {
            get
            {
                return true;
            }
        }

        public override bool IsMainWebPart
        {
            get
            {
                return true;
            }
        }


        [AjaxPro.AjaxMethod]
        public string GetUploadDocumentContentUrl(string belongSite, string NewsId)
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                PermissionTypeCls PermissionTypeCls = Environments.FindPermissionType(
                            new GroupNews().PermissionTypes, "GroupNewsItems");

                NewsCls NewsCls = new NewsBLL().CreateModel(Environments.ActiveLanguage, NewsId);
                Environment.Permission.CheckPermission(Environment.Environments.CurrentLoginUser.LoginName, PermissionTypeCls.PermissionTypeCode, "UpdateNews", NewsCls.GroupNewsItemId, NewsCls.Owner, true);

                return Screen.BuildDialogUrl(new NewsUploadDocument().WebPartId, new ParamCls[]{
                    new ParamCls("belongSite",belongSite),
                    new ParamCls("NewsId",NewsId)
                });
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        [AjaxPro.AjaxMethod]
        public string ServerSideResetDocumentContent(string NewsId, string AttachmentId)
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                new NewsBLL().RemoveSelectedDocumentContent(null, NewsId, AttachmentId);
                return "Thành công loại bỏ nội dung gắn kèm";
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }



        [AjaxPro.AjaxMethod]
        public string ServerSideSaveNewsAttachmentsIndex(string NewsAttachsId, string SortIndex)
        {
            try
            {
                Environments.CheckSessionTimeOut(true);
                new NewsBLL().UpdateNewsAttachmentsSortIndex(NewsAttachsId, SortIndex);
                return "Cập nhật thứ tự hiển thị thành công!";
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }
    }
}